package com.ethen.jzvd;

import com.ethen.jzvd.widget.AlertDialog;
import com.ethen.jzvd.widget.DialogInterface;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.PopupDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.Window;
import ohos.agp.window.service.WindowManager;
import ohos.app.Context;
import ohos.batterymanager.BatteryInfo;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.multimodalinput.event.TouchEvent;
import ohos.net.NetCapabilities;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.net.NetStatusCallback;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayDeque;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;

/**
 * Created by Nathen
 * On 2016/04/18 16:15
 */
public class JzvdStd extends Jzvd {

    public static long LAST_GET_BATTERYLEVEL_TIME = 0;
    public static int LAST_GET_BATTERYLEVEL_PERCENT = 70;
    protected static Timer DISMISS_CONTROL_VIEW_TIMER;

    public Image backButton;
    public ProgressBar bottomProgressBar, loadingProgressBar;
    public Text titleTextView;
    public Image posterImageView;
    public Image tinyBackImageView;
    public DirectionalLayout batteryTimeLayout;
    public Image batteryLevel;
    public Text videoCurrentTime;
    public Text replayTextView;
    public Text clarity;
    public PopupDialog clarityPopWindow;
    public Text mRetryBtn;
    public DirectionalLayout mRetryLayout;
    private NetManager netManager;

    protected DismissControlViewTimerTask mDismissControlViewTimerTask;
    protected CommonDialog mProgressDialog;
    protected ProgressBar mDialogProgressBar;
    protected Text mDialogSeekTime;
    protected Text mDialogTotalTime;
    protected Image mDialogIcon;
    protected CommonDialog mVolumeDialog;
    protected ProgressBar mDialogVolumeProgressBar;
    protected Text mDialogVolumeTextView;
    protected Image mDialogVolumeImageView;
    protected CommonDialog mBrightnessDialog;
    protected ProgressBar mDialogBrightnessProgressBar;
    protected Text mDialogBrightnessTextView;
    protected boolean mIsWifi;

    public NetStatusCallback wifiReceiver = new NetStatusCallback() {
        @Override
        public void onCapabilitiesChanged(NetHandle handle, NetCapabilities networkCapabilities) {
            super.onCapabilitiesChanged(handle, networkCapabilities);

            Log.d(TAG, "intenet changed,but net is ok");
            if (networkCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_VALIDATED)) {
                // 网络连接成功，并且可以上网
                if (networkCapabilities.hasBearer(NetCapabilities.BEARER_WIFI) ||
                        networkCapabilities.hasBearer(NetCapabilities.BEARER_WIFI_AWARE)) {
                    Log.d(TAG, "use wifi to net");

                    boolean isWifi = JZUtils.isWifiConnected(jzvdContext);
                    if (mIsWifi == isWifi) return;
                    mIsWifi = isWifi;
                    if (!mIsWifi && !WIFI_TIP_DIALOG_SHOWED && state == STATE_PLAYING) {
                        startButton.simulateClick();
                        showWifiDialog();
                    }
                } else if (networkCapabilities.hasBearer(NetCapabilities.BEARER_CELLULAR) ||
                        networkCapabilities.hasBearer(NetCapabilities.BEARER_ETHERNET)) {
                    Log.d(TAG, "use mobile phone net");
                } else {
                    // 其它网络，包括蓝牙、VPN、LoWPAN等
                    Log.d(TAG, "use other net");
                }
            }
        }
    };

    protected ArrayDeque<Runnable> delayTask = new ArrayDeque<>();

    public JzvdStd(Context context) {
        super(context);
    }

    public JzvdStd(Context context, AttrSet attrs) {
        super(context, attrs);
    }

    @Override
    public void init(Context context) {
        super.init(context);
        batteryTimeLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_battery_time_layout);
        bottomProgressBar = (ProgressBar) findComponentById(ResourceTable.Id_bottom_progress);
        titleTextView = (Text) findComponentById(ResourceTable.Id_title);
        backButton = (Image) findComponentById(ResourceTable.Id_back);
        posterImageView = (Image) findComponentById(ResourceTable.Id_poster);
        loadingProgressBar = (ProgressBar) findComponentById(ResourceTable.Id_loading);
        tinyBackImageView = (Image) findComponentById(ResourceTable.Id_back_tiny);
        batteryLevel = (Image) findComponentById(ResourceTable.Id_battery_level);
        videoCurrentTime = (Text) findComponentById(ResourceTable.Id_video_current_time);
        replayTextView = (Text) findComponentById(ResourceTable.Id_replay_text);
        clarity = (Text) findComponentById(ResourceTable.Id_clarity);
        mRetryBtn = (Text) findComponentById(ResourceTable.Id_retry_btn);
        mRetryLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_retry_layout);

        if (batteryTimeLayout == null) {
            batteryTimeLayout = new DirectionalLayout(context);
        }
        if (bottomProgressBar == null) {
            bottomProgressBar = new ProgressBar(context);
        }
        if (titleTextView == null) {
            titleTextView = new Text(context);
        }
        if (backButton == null) {
            backButton = new Image(context);
        }
        if (posterImageView == null) {
            posterImageView = new Image(context);
        }
        if (loadingProgressBar == null) {
            loadingProgressBar = new ProgressBar(context);
        }
        if (tinyBackImageView == null) {
            tinyBackImageView = new Image(context);
        }
        if (batteryLevel == null) {
            batteryLevel = new Image(context);
        }
        if (videoCurrentTime == null) {
            videoCurrentTime = new Text(context);
        }
        if (replayTextView == null) {
            replayTextView = new Text(context);
        }
        if (clarity == null) {
            clarity = new Text(context);
        }
        if (mRetryBtn == null) {
            mRetryBtn = new Text(context);
        }
        if (mRetryLayout == null) {
            mRetryLayout = new DirectionalLayout(context);
        }

        posterImageView.setClickedListener(this);
        backButton.setClickedListener(this);
        tinyBackImageView.setClickedListener(this);
        clarity.setClickedListener(this);
        mRetryBtn.setClickedListener(this);
    }

    public void setUp(JZDataSource jzDataSource, int screen, Class mediaInterfaceClass) {
        if ((System.currentTimeMillis() - gobakFullscreenTime) < 200) {
            return;
        }

        if ((System.currentTimeMillis() - gotoFullscreenTime) < 200) {
            return;
        }


        super.setUp(jzDataSource, screen, mediaInterfaceClass);
        titleTextView.setText(jzDataSource.title);
        setScreen(screen);
    }

    @Override
    public void changeUrl(JZDataSource jzDataSource, long seekToInAdvance) {
        super.changeUrl(jzDataSource, seekToInAdvance);
        titleTextView.setText(jzDataSource.title);
    }

    public void changeStartButtonSize(int size) {
        ComponentContainer.LayoutConfig lp = startButton.getLayoutConfig();
        lp.height = size;
        lp.width = size;
        lp = loadingProgressBar.getLayoutConfig();
        lp.height = size;
        lp.width = size;
    }

    @Override
    public int getLayoutId() {
        return ResourceTable.Layout_jz_layout_std;
    }

    @Override
    public void onStateNormal() {
        super.onStateNormal();
        changeUiToNormal();
    }

    @Override
    public void onStatePreparing() {
        super.onStatePreparing();
        changeUiToPreparing();
    }

    public void onStatePreparingPlaying() {
        super.onStatePreparingPlaying();
        changeUIToPreparingPlaying();
    }

    public void onStatePreparingChangeUrl() {
        super.onStatePreparingChangeUrl();
        changeUIToPreparingChangeUrl();
    }

    @Override
    public void onStatePlaying() {
        super.onStatePlaying();
        changeUiToPlayingClear();
    }

    @Override
    public void onStatePause() {
        super.onStatePause();
        changeUiToPauseShow();
        cancelDismissControlViewTimer();
    }

    @Override
    public void onStateError() {
        super.onStateError();
        changeUiToError();
    }

    @Override
    public void onStateAutoComplete() {
        super.onStateAutoComplete();
        changeUiToComplete();
        cancelDismissControlViewTimer();
        bottomProgressBar.setProgressValue(100);
    }

    @Override
    public void startVideo() {
        super.startVideo();
        registerWifiListener(getApplicationContext());
    }

    @Override
    public boolean onTouchEvent(Component v, TouchEvent event) {
        int id = v.getId();
        if (id == ResourceTable.Id_surface_container) {
            switch (event.getAction()) {
                case TouchEvent.PRIMARY_POINT_DOWN:
                case TouchEvent.POINT_MOVE:
                    break;
                case TouchEvent.PRIMARY_POINT_UP:
                    startDismissControlViewTimer();
                    if (mChangePosition) {
                        long duration = getDuration();
                        int progress = (int) (mSeekTimePosition * 100 / (duration == 0 ? 1 : duration));
                        bottomProgressBar.setProgressValue(progress);
                    }
                    break;
            }
        } else if (id == ResourceTable.Id_bottom_seek_progress) {
            switch (event.getAction()) {
                case TouchEvent.PRIMARY_POINT_DOWN:
                    cancelDismissControlViewTimer();
                    break;
                case TouchEvent.PRIMARY_POINT_UP:
                    startDismissControlViewTimer();
                    break;
            }
        }
        return super.onTouchEvent(v, event);
    }

    @Override
    public void onClick(Component v) {
        super.onClick(v);
        int i = v.getId();
        if (i == ResourceTable.Id_poster) {
            clickPoster();
        } else if (i == ResourceTable.Id_surface_container) {
            clickSurfaceContainer();
            if (clarityPopWindow != null) {
                clarityPopWindow.hide();
            }
        } else if (i == ResourceTable.Id_back) {
            clickBack();
        } else if (i == ResourceTable.Id_back_tiny) {
            clickBackTiny();
        } else if (i == ResourceTable.Id_clarity) {
            clickClarity();
        } else if (i == ResourceTable.Id_retry_btn) {
            clickRetryBtn();
        }
    }

    protected void clickRetryBtn() {
        if (jzDataSource.urlsMap.isEmpty() || jzDataSource.getCurrentUrl() == null) {
            String s = getContext().getString(ResourceTable.String_no_url);
            new ToastDialog(getContext()).setText(String.valueOf(s)).setDuration(1000).show();
            return;
        }
        if (!jzDataSource.getCurrentUrl().toString().startsWith("file") && !
                jzDataSource.getCurrentUrl().toString().startsWith("/") &&
                !JZUtils.isWifiConnected(jzvdContext) && !WIFI_TIP_DIALOG_SHOWED) {
            showWifiDialog();
            return;
        }
        seekToInAdvance = mCurrentPosition;
        startVideo();
    }

    protected void clickClarity() {
        onCLickUiToggleToClear();

        final DirectionalLayout layout = (DirectionalLayout) LayoutScatter.getInstance(jzvdContext).parse(ResourceTable.Layout_jz_layout_clarity, null, false);

        Component.ClickedListener mQualityListener = v1 -> {
            int index = (int) v1.getTag();

//                this.seekToInAdvance = getCurrentPositionWhenPlaying();
            jzDataSource.currentUrlIndex = index;
//                onStatePreparingChangeUrl();

            changeUrl(jzDataSource, getCurrentPositionWhenPlaying());

            clarity.setText(jzDataSource.getCurrentKey().toString());
            for (int j = 0; j < layout.getChildCount(); j++) {//设置点击之后的颜色
                if (j == jzDataSource.currentUrlIndex) {
                    ((Text) layout.getComponentAt(j)).setTextColor(new Color(Color.getIntColor("#fff85959")));
                } else {
                    ((Text) layout.getComponentAt(j)).setTextColor(new Color(Color.getIntColor("#ffffff")));
                }
            }
            if (clarityPopWindow != null) {
                clarityPopWindow.hide();
            }
        };

        for (int j = 0; j < jzDataSource.urlsMap.size(); j++) {
            String key = jzDataSource.getKeyFromDataSource(j);
            Text clarityItem = (Text) LayoutScatter.getInstance(jzvdContext)
                    .parse(ResourceTable.Layout_jz_layout_clarity_item, null, false);
            clarityItem.setText(key);
            clarityItem.setTag(j);
            layout.addComponent(clarityItem, j);
            clarityItem.setClickedListener(mQualityListener);
            if (j == jzDataSource.currentUrlIndex) {
                clarityItem.setTextColor(new Color(Color.getIntColor("#fff85959")));
            }
        }

        clarityPopWindow = new PopupDialog(jzvdContext,layout, JZUtils.dip2px(jzvdContext, 240), LayoutConfig.MATCH_PARENT);
        clarityPopWindow.showOnCertainPosition(LayoutAlignment.END, textureViewContainer.getLeft(), textureViewContainer.getTop());
//            int offsetX = clarity.getMeasuredWidth() / 3;
//            int offsetY = clarity.getMeasuredHeight() / 3;
//            clarityPopWindow.update(clarity, -offsetX, -offsetY, Math.round(layout.getMeasuredWidth() * 2), layout.getMeasuredHeight());
    }

    protected void clickBackTiny() {
        clearFloatScreen();
    }

    protected void clickBack() {
        backPress();
    }

    protected void clickSurfaceContainer() {
        startDismissControlViewTimer();
    }

    protected void clickPoster() {
        if (jzDataSource == null || jzDataSource.urlsMap.isEmpty() || jzDataSource.getCurrentUrl() == null) {
            String s = getContext().getString(ResourceTable.String_no_url);
            new ToastDialog(getContext()).setText(String.valueOf(s)).setDuration(1000).show();
            return;
        }
        if (state == STATE_NORMAL) {
            if (!jzDataSource.getCurrentUrl().toString().startsWith("file") &&
                    !jzDataSource.getCurrentUrl().toString().startsWith("/") &&
                    !JZUtils.isWifiConnected(jzvdContext) && !WIFI_TIP_DIALOG_SHOWED) {
                showWifiDialog();
                return;
            }
            startVideo();
        } else if (state == STATE_AUTO_COMPLETE) {
            onClickUiToggle();
        }
    }

    @Override
    public void setScreenNormal() {
        super.setScreenNormal();
        fullscreenButton.setPixelMap(ResourceTable.Media_jz_enlarge);
        backButton.setVisibility(HIDE);
        tinyBackImageView.setVisibility(INVISIBLE);
        int textSize = getElementSize(ResourceTable.Integer_jz_start_button_w_h_normal);
        changeStartButtonSize(textSize);
        batteryTimeLayout.setVisibility(HIDE);
        clarity.setVisibility(HIDE);
    }

    @Override
    public void setScreenFullscreen() {
        super.setScreenFullscreen();
        //进入全屏之后要保证原来的播放状态和ui状态不变，改变个别的ui
        fullscreenButton.setPixelMap(ResourceTable.Media_jz_shrink);
        backButton.setVisibility(VISIBLE);
        tinyBackImageView.setVisibility(INVISIBLE);
        batteryTimeLayout.setVisibility(VISIBLE);
        if (jzDataSource.urlsMap.size() == 1) {
            clarity.setVisibility(HIDE);
        } else {
            clarity.setText(jzDataSource.getCurrentKey().toString());
            clarity.setVisibility(VISIBLE);
        }
        int textSize = getElementSize(ResourceTable.Integer_jz_start_button_w_h_fullscreen);
        changeStartButtonSize(textSize);
        setSystemTimeAndBattery();
    }

    public int getElementSize(int resID){
        int textSize = 0;
        try {
            textSize = getResourceManager().getElement(resID).getInteger();
            changeStartButtonSize(textSize);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        } catch (WrongTypeException e) {
            e.printStackTrace();
        }
        return textSize;
    }

    @Override
    public void setScreenTiny() {
        super.setScreenTiny();
        tinyBackImageView.setVisibility(VISIBLE);
        setAllControlsVisiblity(INVISIBLE, INVISIBLE, INVISIBLE,
                INVISIBLE, INVISIBLE, INVISIBLE, INVISIBLE);
        batteryTimeLayout.setVisibility(HIDE);
        clarity.setVisibility(HIDE);
    }

    @Override
    public void showWifiDialog() {
        super.showWifiDialog();

        AlertDialog.Builder builder = new AlertDialog.Builder(jzvdContext);
        builder.setMessage(ResourceTool.getString(jzvdContext,ResourceTable.String_tips_not_wifi,null));
        builder.setPositiveButton(ResourceTool.getString(jzvdContext, ResourceTable.String_tips_not_wifi_confirm, null), (dialog, which) -> {
                    dialog.dismiss();
                    WIFI_TIP_DIALOG_SHOWED = true;
                    if (state == STATE_PAUSE) {
                        startButton.simulateClick();
                    } else {
                        startVideo();
                    }
                });


        builder.setNegativeButton(ResourceTool.getString(jzvdContext, ResourceTable.String_tips_not_wifi_cancel, null), (dialog, which) -> {
            dialog.dismiss();
            releaseAllVideos();
            clearFloatScreen();
        });

        builder.setOnCancelListener((dialog, which) -> {
            dialog.dismiss();
            releaseAllVideos();
            clearFloatScreen();
        });

        builder.create().show();
    }

    @Override
    public void onTouchStart(Slider seekBar) {
        super.onTouchStart(seekBar);
        cancelDismissControlViewTimer();
    }

    @Override
    public void onTouchEnd(Slider seekBar) {
        super.onTouchEnd(seekBar);
        startDismissControlViewTimer();
    }

    public void onClickUiToggle() {//这是事件
        if (bottomContainer.getVisibility() != VISIBLE) {
            setSystemTimeAndBattery();
            clarity.setText(jzDataSource.getCurrentKey().toString());
        }
        if (state == STATE_PREPARING) {
            changeUiToPreparing();
            if (bottomContainer.getVisibility() == VISIBLE) {
            } else {
                setSystemTimeAndBattery();
            }
        } else if (state == STATE_PLAYING) {
            if (bottomContainer.getVisibility() == VISIBLE) {
                changeUiToPlayingClear();
            } else {
                changeUiToPlayingShow();
            }
        } else if (state == STATE_PAUSE) {
            if (bottomContainer.getVisibility() == VISIBLE) {
                changeUiToPauseClear();
            } else {
                changeUiToPauseShow();
            }
        }
    }

    public void setSystemTimeAndBattery() {
        SimpleDateFormat dateFormater = new SimpleDateFormat("HH:mm");
        Date date = new Date();
        videoCurrentTime.setText(dateFormater.format(date));
        if ((System.currentTimeMillis() - LAST_GET_BATTERYLEVEL_TIME) > 30000) {
            LAST_GET_BATTERYLEVEL_TIME = System.currentTimeMillis();
            BatteryInfo batteryInfo = new BatteryInfo();
            LAST_GET_BATTERYLEVEL_PERCENT = batteryInfo.getCapacity();
        }

        setBatteryLevel();
    }

    public void setBatteryLevel() {
        int percent = LAST_GET_BATTERYLEVEL_PERCENT;
        if (percent < 15) {
            batteryLevel.setPixelMap(ResourceTable.Media_jz_battery_level_10);
        } else if (percent < 40) {
            batteryLevel.setPixelMap(ResourceTable.Media_jz_battery_level_30);
        } else if (percent < 60) {
            batteryLevel.setPixelMap(ResourceTable.Media_jz_battery_level_50);
        } else if (percent < 80) {
            batteryLevel.setPixelMap(ResourceTable.Media_jz_battery_level_70);
        } else if (percent < 95) {
            batteryLevel.setPixelMap(ResourceTable.Media_jz_battery_level_90);
        } else if (percent <= 100) {
            batteryLevel.setPixelMap(ResourceTable.Media_jz_battery_level_100);
        }
    }

    //** 和onClickUiToggle重复，要干掉
    public void onCLickUiToggleToClear() {
        if (state == STATE_PREPARING) {
            if (bottomContainer.getVisibility() == VISIBLE) {
                changeUiToPreparing();
            } else {
            }
        } else if (state == STATE_PLAYING) {
            if (bottomContainer.getVisibility() == VISIBLE) {
                changeUiToPlayingClear();
            } else {
            }
        } else if (state == STATE_PAUSE) {
            if (bottomContainer.getVisibility() == VISIBLE) {
                changeUiToPauseClear();
            } else {
            }
        } else if (state == STATE_AUTO_COMPLETE) {
            if (bottomContainer.getVisibility() == VISIBLE) {
                changeUiToComplete();
            } else {
            }
        }
    }

    @Override
    public void onProgress(int progress, long position, long duration) {
        super.onProgress(progress, position, duration);
        bottomProgressBar.setProgressValue(progress);
    }

    @Override
    public void setBufferProgress(int bufferProgress) {
        super.setBufferProgress(bufferProgress);
        bottomProgressBar.setViceProgress(bufferProgress);
    }

    @Override
    public void resetProgressAndTime() {
        super.resetProgressAndTime();
        bottomProgressBar.setProgressValue(0);
        bottomProgressBar.setViceProgress(0);
    }

    public void changeUiToNormal() {
        switch (screen) {
            case SCREEN_NORMAL:
            case SCREEN_FULLSCREEN:
                setAllControlsVisiblity(VISIBLE, INVISIBLE, VISIBLE,
                        INVISIBLE, VISIBLE, INVISIBLE, INVISIBLE);
                updateStartImage();
                break;
            case SCREEN_TINY:
                break;
        }
    }

    public void changeUiToPreparing() {
        switch (screen) {
            case SCREEN_NORMAL:
            case SCREEN_FULLSCREEN:
                setAllControlsVisiblity(INVISIBLE, INVISIBLE, INVISIBLE,
                        VISIBLE, VISIBLE, INVISIBLE, INVISIBLE);
                updateStartImage();
                break;
            case SCREEN_TINY:
                break;
        }
    }

    public void changeUIToPreparingPlaying() {
        switch (screen) {
            case SCREEN_NORMAL:
            case SCREEN_FULLSCREEN:
                setAllControlsVisiblity(VISIBLE, VISIBLE, INVISIBLE,
                        VISIBLE, INVISIBLE, INVISIBLE, INVISIBLE);
                updateStartImage();
                break;
            case SCREEN_TINY:
                break;
        }
    }

    public void changeUIToPreparingChangeUrl() {
        switch (screen) {
            case SCREEN_NORMAL:
            case SCREEN_FULLSCREEN:
                setAllControlsVisiblity(INVISIBLE, INVISIBLE, INVISIBLE,
                        VISIBLE, VISIBLE, INVISIBLE, INVISIBLE);
                updateStartImage();
                break;
            case SCREEN_TINY:
                break;
        }
    }

    public void changeUiToPlayingShow() {
        switch (screen) {
            case SCREEN_NORMAL:
            case SCREEN_FULLSCREEN:
                setAllControlsVisiblity(VISIBLE, VISIBLE, VISIBLE,
                        INVISIBLE, INVISIBLE, INVISIBLE, INVISIBLE);
                updateStartImage();
                break;
            case SCREEN_TINY:
                break;
        }

    }

    public void changeUiToPlayingClear() {
        switch (screen) {
            case SCREEN_NORMAL:
            case SCREEN_FULLSCREEN:
                setAllControlsVisiblity(INVISIBLE, INVISIBLE, INVISIBLE,
                        INVISIBLE, INVISIBLE, VISIBLE, INVISIBLE);
                break;
            case SCREEN_TINY:
                break;
        }

    }

    public void changeUiToPauseShow() {
        switch (screen) {
            case SCREEN_NORMAL:
            case SCREEN_FULLSCREEN:
                setAllControlsVisiblity(VISIBLE, VISIBLE, VISIBLE,
                        INVISIBLE, INVISIBLE, INVISIBLE, INVISIBLE);
                updateStartImage();
                break;
            case SCREEN_TINY:
                break;
        }
    }

    public void changeUiToPauseClear() {
        switch (screen) {
            case SCREEN_NORMAL:
            case SCREEN_FULLSCREEN:
                setAllControlsVisiblity(INVISIBLE, INVISIBLE, INVISIBLE,
                        INVISIBLE, INVISIBLE, VISIBLE, INVISIBLE);
                break;
            case SCREEN_TINY:
                break;
        }

    }

    public void changeUiToComplete() {
        switch (screen) {
            case SCREEN_NORMAL:
            case SCREEN_FULLSCREEN:
                setAllControlsVisiblity(VISIBLE, INVISIBLE, VISIBLE,
                        INVISIBLE, VISIBLE, INVISIBLE, INVISIBLE);
                updateStartImage();
                break;
            case SCREEN_TINY:
                break;
        }

    }

    public void changeUiToError() {
        switch (screen) {
            case SCREEN_NORMAL:
                setAllControlsVisiblity(INVISIBLE, INVISIBLE, VISIBLE,
                        INVISIBLE, INVISIBLE, INVISIBLE, VISIBLE);
                updateStartImage();
                break;
            case SCREEN_FULLSCREEN:
                setAllControlsVisiblity(VISIBLE, INVISIBLE, VISIBLE,
                        INVISIBLE, INVISIBLE, INVISIBLE, VISIBLE);
                updateStartImage();
                break;
            case SCREEN_TINY:
                break;
        }

    }

    public void setAllControlsVisiblity(int topCon, int bottomCon, int startBtn, int loadingPro,
                                        int posterImg, int bottomPro, int retryLayout) {
        topContainer.setVisibility(topCon);
        bottomContainer.setVisibility(bottomCon);
        startButton.setVisibility(startBtn);
        loadingProgressBar.setVisibility(loadingPro);
        posterImageView.setVisibility(posterImg);
        bottomProgressBar.setVisibility(bottomPro);
        mRetryLayout.setVisibility(retryLayout);
    }

    public void updateStartImage() {
        if (state == STATE_PLAYING) {
            startButton.setVisibility(VISIBLE);
            startButton.setPixelMap(ResourceTable.Graphic_jz_click_pause_selector);
            replayTextView.setVisibility(HIDE);
        } else if (state == STATE_ERROR) {
            startButton.setVisibility(INVISIBLE);
            replayTextView.setVisibility(HIDE);
        } else if (state == STATE_AUTO_COMPLETE) {
            startButton.setVisibility(VISIBLE);
            startButton.setPixelMap(ResourceTable.Graphic_jz_click_replay_selector);
            replayTextView.setVisibility(VISIBLE);
        } else {
            startButton.setPixelMap(ResourceTable.Graphic_jz_click_play_selector);
            replayTextView.setVisibility(HIDE);
        }
    }

    @Override
    public void showProgressDialog(float deltaX, String seekTime, long seekTimePosition, String totalTime, long totalTimeDuration) {
        super.showProgressDialog(deltaX, seekTime, seekTimePosition, totalTime, totalTimeDuration);
        if (mProgressDialog == null) {
            Component localView = LayoutScatter.getInstance(jzvdContext).parse(ResourceTable.Layout_jz_dialog_progress, null, false);
            mDialogProgressBar = (ProgressBar) localView.findComponentById(ResourceTable.Id_duration_progressbar);
            mDialogSeekTime = (Text) localView.findComponentById(ResourceTable.Id_tv_current);
            mDialogTotalTime = (Text) localView.findComponentById(ResourceTable.Id_tv_duration);
            mDialogIcon = (Image) localView.findComponentById(ResourceTable.Id_duration_image_tip);
            mProgressDialog = createDialogWithView(localView);
        }
        if (!mProgressDialog.isShowing()) {
            mProgressDialog.show();
        }

        mDialogSeekTime.setText(seekTime);
        mDialogTotalTime.setText(" / " + totalTime);
        mDialogProgressBar.setProgressValue(totalTimeDuration <= 0 ? 0 : (int) (seekTimePosition * 100 / totalTimeDuration));
        if (deltaX > 0) {
            mDialogIcon.setPixelMap(ResourceTable.Media_jz_forward_icon);
        } else {
            mDialogIcon.setPixelMap(ResourceTable.Media_jz_backward_icon);
        }
        onCLickUiToggleToClear();
    }

    @Override
    public void dismissProgressDialog() {
        super.dismissProgressDialog();
        if (mProgressDialog != null) {
            mProgressDialog.hide();
        }
    }

    @Override
    public void showVolumeDialog(float deltaY, int volumePercent) {
        super.showVolumeDialog(deltaY, volumePercent);
        if (mVolumeDialog == null) {
            Component localView = LayoutScatter.getInstance(jzvdContext).parse(ResourceTable.Layout_jz_dialog_volume, null, false);
            mDialogVolumeImageView = (Image) localView.findComponentById(ResourceTable.Id_volume_image_tip);
            mDialogVolumeTextView = (Text) localView.findComponentById(ResourceTable.Id_tv_volume);
            mDialogVolumeProgressBar = (ProgressBar) localView.findComponentById(ResourceTable.Id_volume_progressbar);
            mVolumeDialog = createDialogWithView(localView);
        }
        if (!mVolumeDialog.isShowing()) {
            mVolumeDialog.show();
        }
        if (volumePercent <= 0) {
            mDialogVolumeImageView.setPixelMap(ResourceTable.Media_jz_close_volume);
        } else {
            mDialogVolumeImageView.setPixelMap(ResourceTable.Media_jz_add_volume);
        }
        if (volumePercent > 100) {
            volumePercent = 100;
        } else if (volumePercent < 0) {
            volumePercent = 0;
        }
        mDialogVolumeTextView.setText(volumePercent + "%");
        mDialogVolumeProgressBar.setProgressValue(volumePercent);
        onCLickUiToggleToClear();
    }

    @Override
    public void dismissVolumeDialog() {
        super.dismissVolumeDialog();
        if (mVolumeDialog != null) {
            mVolumeDialog.hide();
        }
    }

    @Override
    public void showBrightnessDialog(int brightnessPercent) {
        super.showBrightnessDialog(brightnessPercent);
        if (mBrightnessDialog == null) {
            Component localView = LayoutScatter.getInstance(jzvdContext).parse(ResourceTable.Layout_jz_dialog_brightness, null, false);
            mDialogBrightnessTextView = (Text) localView.findComponentById(ResourceTable.Id_tv_brightness);
            mDialogBrightnessProgressBar = (ProgressBar) localView.findComponentById(ResourceTable.Id_brightness_progressbar);
            mBrightnessDialog = createDialogWithView(localView);
        }
        if (!mBrightnessDialog.isShowing()) {
            mBrightnessDialog.show();
        }
        if (brightnessPercent > 100) {
            brightnessPercent = 100;
        } else if (brightnessPercent < 0) {
            brightnessPercent = 0;
        }
        mDialogBrightnessTextView.setText(brightnessPercent + "%");
        mDialogBrightnessProgressBar.setProgressValue(brightnessPercent);
        onCLickUiToggleToClear();
    }

    @Override
    public void dismissBrightnessDialog() {
        super.dismissBrightnessDialog();
        if (mBrightnessDialog != null) {
            mBrightnessDialog.hide();
        }
    }

    public CommonDialog createDialogWithView(Component localView) {
        CommonDialog dialog = new CommonDialog(jzvdContext);
        dialog.setContentCustomComponent(localView);
        dialog.setSize(MATCH_CONTENT,MATCH_CONTENT);
        Window window = dialog.getWindow();
        window.addFlags(WindowManager.LayoutConfig.MOD_STATUS_BAR);
        window.addFlags(WindowManager.LayoutConfig.MARK_TOUCH_MODAL_IMPOSSIBLE);
        window.addFlags(WindowManager.LayoutConfig.MARK_TOUCHABLE_IMPOSSIBLE);
        WindowManager.LayoutConfig localLayoutParams = window.getLayoutConfig().get();
        localLayoutParams.alignment = LayoutAlignment.CENTER;
        window.setLayoutConfig(localLayoutParams);
        return dialog;
    }

    public void startDismissControlViewTimer() {
        cancelDismissControlViewTimer();
        DISMISS_CONTROL_VIEW_TIMER = new Timer();
        mDismissControlViewTimerTask = new DismissControlViewTimerTask();
        DISMISS_CONTROL_VIEW_TIMER.schedule(mDismissControlViewTimerTask, 2500);
    }

    public void cancelDismissControlViewTimer() {
        if (DISMISS_CONTROL_VIEW_TIMER != null) {
            DISMISS_CONTROL_VIEW_TIMER.cancel();
        }
        if (mDismissControlViewTimerTask != null) {
            mDismissControlViewTimerTask.cancel();
        }

    }

    @Override
    public void onCompletion() {
        super.onCompletion();
        cancelDismissControlViewTimer();
    }

    @Override
    public void reset() {
        super.reset();
        cancelDismissControlViewTimer();
        unregisterWifiListener(getApplicationContext());
    }

    public void dissmissControlView() {
        if (state != STATE_NORMAL
                && state != STATE_ERROR
                && state != STATE_AUTO_COMPLETE) {
            handler.postTask(() -> {
                bottomContainer.setVisibility(INVISIBLE);
                topContainer.setVisibility(INVISIBLE);
                startButton.setVisibility(INVISIBLE);

                if (screen != SCREEN_TINY) {
                    bottomProgressBar.setVisibility(VISIBLE);
                }
            });
        }
    }

    public void registerWifiListener(Context context) {
        if (context == null) return;
        mIsWifi = JZUtils.isWifiConnected(context);
        // 获取网络管理对象
        netManager = NetManager.getInstance(jzvdContext);
        // 添加监听，监听实时的网络状态
        netManager.addDefaultNetStatusCallback(wifiReceiver);
    }

    public void unregisterWifiListener(Context context) {
        if (context == null) return;
        if (netManager != null) {
            // 移除监听
            netManager.removeNetStatusCallback(wifiReceiver);
        }
    }

    public class DismissControlViewTimerTask extends TimerTask {

        @Override
        public void run() {
            dissmissControlView();
        }
    }

}
